<template>
  <div class="system-log">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="操作人">
          <el-input 
            v-model="searchForm.operator" 
            placeholder="请输入操作人" 
            clearable 
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="操作模块">
          <el-select v-model="searchForm.module" placeholder="请选择" clearable>
            <el-option label="用户管理" value="user" />
            <el-option label="角色管理" value="role" />
            <el-option label="权限管理" value="permission" />
            <el-option label="洗护管理" value="wash" />
            <el-option label="订单管理" value="order" />
            <el-option label="系统配置" value="config" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.action" placeholder="请选择" clearable>
            <el-option label="查看" value="view" />
            <el-option label="新增" value="create" />
            <el-option label="编辑" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="登录" value="login" />
            <el-option label="登出" value="logout" />
          </el-select>
        </el-form-item>
        <el-form-item label="日志级别">
          <el-select v-model="searchForm.level" placeholder="请选择" clearable>
            <el-option label="信息" value="info" />
            <el-option label="警告" value="warn" />
            <el-option label="错误" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出日志
        </el-button>
        <el-button type="danger" @click="handleCleanLogs">
          <el-icon><Delete /></el-icon>
          清理日志
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 日志列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        size="small"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="operator" label="操作人" width="100" />
        <el-table-column prop="module" label="操作模块" width="100">
          <template #default="{ row }">
            <el-tag size="small">{{ getModuleText(row.module) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="action" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getActionType(row.action)" size="small">
              {{ getActionText(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="level" label="日志级别" width="80">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)" size="small">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="120" />
        <el-table-column prop="userAgent" label="用户代理" width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="操作时间" width="160" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="getLogData"
          @size-change="getLogData"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="操作ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ currentLog.operator }}</el-descriptions-item>
        <el-descriptions-item label="操作模块">{{ getModuleText(currentLog.module) }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{ getActionText(currentLog.action) }}</el-descriptions-item>
        <el-descriptions-item label="日志级别">{{ getLevelText(currentLog.level) }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
        <el-descriptions-item label="操作时间" :span="2">{{ currentLog.createTime }}</el-descriptions-item>
        <el-descriptions-item label="操作描述" :span="2">{{ currentLog.description }}</el-descriptions-item>
        <el-descriptions-item label="用户代理" :span="2">{{ currentLog.userAgent }}</el-descriptions-item>
      </el-descriptions>
      
      <div style="margin-top: 20px;" v-if="currentLog.requestData">
        <h4>请求参数</h4>
        <el-input
          v-model="currentLog.requestData"
          type="textarea"
          :rows="6"
          readonly
        />
      </div>
      
      <div style="margin-top: 20px;" v-if="currentLog.responseData">
        <h4>响应数据</h4>
        <el-input
          v-model="currentLog.responseData"
          type="textarea"
          :rows="6"
          readonly
        />
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 清理日志对话框 -->
    <el-dialog
      v-model="clearDialogVisible"
      title="清理日志"
      width="500px"
    >
      <el-form :model="clearForm" label-width="120px">
        <el-form-item label="清理方式">
          <el-radio-group v-model="clearForm.type">
            <el-radio label="days">按天数清理</el-radio>
            <el-radio label="count">按数量清理</el-radio>
            <el-radio label="all">清理全部</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="保留天数" v-if="clearForm.type === 'days'">
          <el-input-number v-model="clearForm.days" :min="1" :max="365" />
          <span style="margin-left: 10px;">天</span>
        </el-form-item>
        <el-form-item label="保留数量" v-if="clearForm.type === 'count'">
          <el-input-number v-model="clearForm.count" :min="100" :max="100000" />
          <span style="margin-left: 10px;">条</span>
        </el-form-item>
      </el-form>
      <el-alert
        title="警告：清理操作不可恢复，请谨慎操作！"
        type="warning"
        :closable="false"
        style="margin-top: 20px;"
      />
      <template #footer>
        <el-button @click="clearDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleConfirmClear" :loading="clearLoading">
          确认清理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Delete } from '@element-plus/icons-vue'
import { getSystemLogs, exportSystemLogs } from '@/api/wash_service'

export default {
  name: 'SystemLog',
  components: {
    Search, Refresh, Download, Delete
  },
  setup() {
    const loading = ref(false)
    const clearLoading = ref(false)
    const detailDialogVisible = ref(false)
    const clearDialogVisible = ref(false)

    const searchForm = reactive({
      operator: '',
      module: '',
      action: '',
      level: '',
      dateRange: []
    })

    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    const clearForm = reactive({
      type: 'days',
      days: 30,
      count: 10000
    })

    const tableData = ref([])
    const currentLog = ref({})

    // 模块映射
    const moduleMap = {
      user: '用户管理',
      role: '角色管理',
      permission: '权限管理',
      wash: '洗护管理',
      order: '订单管理',
      config: '系统配置'
    }

    // 操作类型映射
    const actionMap = {
      view: '查看',
      create: '新增',
      update: '编辑',
      delete: '删除',
      login: '登录',
      logout: '登出'
    }

    // 日志级别映射
    const levelMap = {
      info: '信息',
      warn: '警告',
      error: '错误'
    }

    // 获取日志列表
    const getLogData = async () => {
      loading.value = true
      try {
        const res = await getSystemLogs({
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        })
        
        if (res.code === 200) {
          tableData.value = res.data.records || []
          pagination.total = res.data.total || 0
        }
      } catch (error) {
        console.error('获取系统日志失败:', error)
        ElMessage.error('获取系统日志失败')
      } finally {
        loading.value = false
      }
    }

    // 获取模块文本
    const getModuleText = (module) => {
      return moduleMap[module] || module
    }

    // 获取操作类型文本
    const getActionText = (action) => {
      return actionMap[action] || action
    }

    // 获取操作类型标签类型
    const getActionType = (action) => {
      const typeMap = {
        view: '',
        create: 'success',
        update: 'warning',
        delete: 'danger',
        login: 'primary',
        logout: 'info'
      }
      return typeMap[action] || ''
    }

    // 获取日志级别文本
    const getLevelText = (level) => {
      return levelMap[level] || level
    }

    // 获取日志级别标签类型
    const getLevelType = (level) => {
      const typeMap = {
        info: 'primary',
        warn: 'warning',
        error: 'danger'
      }
      return typeMap[level] || 'primary'
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      getLogData()
    }

    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        operator: '',
        module: '',
        action: '',
        level: '',
        dateRange: []
      })
      handleSearch()
    }

    // 刷新
    const handleRefresh = () => {
      getLogData()
    }

    // 查看详情
    const handleViewDetail = async (row) => {
      currentLog.value = row
      detailDialogVisible.value = true
    }

    // 导出日志
    const handleExport = async () => {
      try {
        const res = await exportSystemLogs(searchForm)
        // 处理文件下载
        ElMessage.success('导出成功')
      } catch (error) {
        ElMessage.error('导出失败')
      }
    }

    // 清理日志
    const handleCleanLogs = async () => {
      try {
        await ElMessageBox.confirm('确定要清理30天前的日志吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await updateSystemConfig({
          action: 'clean_logs',
          days: 30
        })
        
        if (res.code === 200) {
          ElMessage.success('日志清理成功')
          getLogData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('日志清理失败')
        }
      }
    }

    onMounted(() => {
      getLogData()
    })

    return {
      loading,
      clearLoading,
      detailDialogVisible,
      clearDialogVisible,
      searchForm,
      pagination,
      clearForm,
      tableData,
      currentLog,
      getLogData,
      getModuleText,
      getActionText,
      getActionType,
      getLevelText,
      getLevelType,
      handleSearch,
      handleReset,
      handleRefresh,
      handleViewDetail,
      handleExport,
      handleCleanLogs
    }
  }
}
</script>

<style scoped>
.system-log {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 